import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:pax_info_app/ui/widgets/Animation/FadeAnimation.dart';
import 'package:pax_info_app/model/clock_user_info.dart';
import 'package:pax_info_app/model/sys_info.dart';
import 'package:pax_info_app/provider/provider_widget.dart';
import 'package:pax_info_app/provider/view_state_widget.dart';
import 'package:pax_info_app/repository/app_repository.dart';
import 'package:pax_info_app/ui/pages/login_page.dart';
import 'package:pax_info_app/ui/view_model/clock_model.dart';
import 'package:pax_info_app/utils/uidata.dart';

class ClockPage extends StatelessWidget {
  final int userNo;
  final String fDate;
  const ClockPage(this.userNo, this.fDate, {Key? key});

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: UIData.windowBg,
      appBar: AppBar(
        backgroundColor: const Color.fromRGBO(143, 148, 251, 1),
        title: const Text('我要打卡'),
      ),
      body: ProviderWidget<ClockModel>(
        model: ClockModel(userNo, fDate),
        onModelReady: (model) => model.initData(),
        builder: (context, model, child) {

          if (model.isBusy) {
            return ViewStateBusyWidget();
          }
          if (model.isError) {
            return ViewStateErrorWidget(error: model.viewStateError, onPressed: model.initData);
          }
          if (model.isEmpty) {
            // return ViewStateEmptyWidget(onPressed: model.initData);
            return Padding(
              padding: const EdgeInsets.all(15.0),
              child: Column(
                children: [
                  const SizedBox(height: 50.0,),
                  FadeAnimation(0,  Center(
                    child: _buildBtn(context, model),
                  ),)
                ],
              ),
            );
          }
          ClockUserInfo clockUserInfo = model.clockUserInfo;

          return SingleChildScrollView(
            padding: const EdgeInsets.all(15.0),
            child: Column(
              children: [
                _buildUserInfo(clockUserInfo.userName??'', clockUserInfo.unitName??''),
                const SizedBox(height: 10.0,),
                Card(
                  color: Colors.white,
                  elevation: 0.0, //设置阴影
                  shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.0))), //设置圆角
                  child: Padding(
                    padding: const EdgeInsets.all(15.0),
                    child: Column(
                      children: [
                        Row(
                          children: [
                            _buildLittleCard(title: '上班：09:00',
                                subTitle: clockUserInfo.fAM??'未打卡',
                                type: clockUserInfo.fAMType
                            ),
                            const Expanded(child: Text('')),
                            _buildLittleCard(title: '下班：18:00',
                                subTitle: clockUserInfo.fPMType??'未打卡',
                                type: clockUserInfo.fPMType
                            ),
                          ],
                        ),
                        // Cell(title: '时间', value: '${model.currentDateTime} ${model.weekDay}'),
                        // Cell(title: '姓名', value: '${clockUserInfo.userName}'),
                        // Cell(title: '部门', value: '${clockUserInfo.unitName}'),
                        // Cell(title: '网络', value: '${clockUserInfo.ip}'),
                        // Cell(title: '上班', value: '${clockUserInfo.fAMType}'),
                        // Cell(title: '下班', value: '${clockUserInfo.fPMType}'),


                        const SizedBox(height: 50.0,),
                        FadeAnimation(0, _buildBtn(context, model),),
                        const SizedBox(height: 20.0,),
                        FadeAnimation(0, Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Image.asset(UIData.checkCircleGreen, width: 18.0,),
                            const SizedBox(width: 4.0,),
                            Text('已进入考勤范围，网络：${clockUserInfo.ip}', style: const TextStyle(
                              fontSize: 14.0,
                            ),),
                          ],
                        ),),
                        const SizedBox(height: 10.0,),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildUserInfo(String userName, String unitName) {
    return Card(
      color: Colors.white,
      elevation: 0.0, //设置阴影
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.0))), //设置圆角
      child: Padding(
        padding: const EdgeInsets.all(15.0),
        child: Row(
          children: [
            Image.asset(UIData.avatar, width: 60.0,),
            const SizedBox(width: 10.0,),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(userName, style: const TextStyle(
                    color: UIData.black,
                    fontSize: 18.0
                ),),
                const SizedBox(height: 2.0,),
                Text(unitName, style: const TextStyle(
                    fontSize: 14.0
                ),),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLittleCard({
    required String title,
    required String subTitle,
    String? type }) {
    double w = (SysInfo.instance.deviceSize.width - 80) / 2;
    final subTitleStyle = const TextStyle(
      color: UIData.textGD,
      fontSize: 14.0,
    );
    return Container(
      width: w,
      padding: const EdgeInsets.all(10.0),
      decoration: BoxDecoration(
        color: UIData.lineBg,
        borderRadius: BorderRadius.circular(5),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(title, style: const TextStyle(
              fontSize: 16.0
          ),),
          const SizedBox(height: 5.0,),
          Row(
            children: [
              _buildIcon(type??''),
              Text(subTitle, style: subTitleStyle,),
              _buildType(type??''),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildIcon(String type) {
    if (type.contains('正常')) {
      return Container(
        margin: EdgeInsets.only(right: 5.0),
        child: Image.asset(UIData.checkCirclePurple, width: 16.0,),
      );
    }
    return Container();
  }

  Widget _buildType(String type) {
    if (type.contains('正常')) {
      return Container(
        margin: EdgeInsets.only(left: 2.0),
        padding: EdgeInsets.symmetric(horizontal: 2.0),
        decoration: BoxDecoration(
          border: Border.all(color: UIData.primaryColor, width: 0.5),
          borderRadius: BorderRadius.circular(5),
        ),
        child: Text('正常', style: TextStyle(
            fontSize: 10.0,
            color: UIData.primaryColor
        ),),
      );
    }
    return Container();
  }

  Widget _buildBtn(BuildContext context, ClockModel model) {
    final ButtonStyle buttonStyle =
    ElevatedButton.styleFrom(
      primary: Colors.transparent,
      textStyle: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
      shape: CircleBorder(),
      padding: EdgeInsets.all(10.0),
    );
    return Container(
      width: 150.0,
      height: 150.0,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(75),
        gradient: RadialGradient(colors: [
          Color.fromRGBO(143, 148, 251, 1),
          Color.fromRGBO(143, 148, 251, .8),]),
      ),
      child: ElevatedButton(
        onPressed: () => (SysInfo.instance.needPhoto??true)
            ? chooseImage(context, model)
            : model.matchPerson(context, userName: model.clockUserInfo.userName),
        style: buttonStyle,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text("${model.clockUserInfo.buttonName??'打卡'}"),
            SizedBox(height: 5.0,),
            Text("${model.currentTime}", style: TextStyle(
              fontSize: 16.0,
              color: Color(0xfff3e5f5),
              fontWeight: FontWeight.normal,
            ),),
          ],
        ),
      ),
    );
  }

  void chooseImage(BuildContext ctx, ClockModel model) async {
    final picker = ImagePicker();

    showModalBottomSheet(
        context: ctx,
        builder: (BuildContext context) {
          return Stack(
            children: [
              Container(
                height: 30.0,
                width: double.infinity,
                color: Colors.black54,
              ),

              Container(
                decoration: const BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(10),
                      topRight: Radius.circular(10),
                    )
                ),

                child: Column(
                  mainAxisSize: MainAxisSize.min, // 设置最小的弹出
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () async {
                        var imageFile = await picker.pickImage(source: ImageSource.camera);
                        CroppedFile? cropImageFile = await _cropImage(File(imageFile!.path));
                        if (cropImageFile != null) {
                          model.pickImage(ctx, File(cropImageFile.path));
                          Navigator.pop(context);
                        }
                      },
                      child: Container(
                        width: SysInfo.instance.deviceSize.width,
                        height: 60.0,
                        decoration: const BoxDecoration(
                            border: Border(
                                bottom: BorderSide(color: UIData.lineBg, width: UIData.lineH)
                            )
                        ),
                        child: const Text('相机',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              height: 3.0,
                              fontSize: 16.0
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () async {
                        var imageFile = await picker.pickImage(source: ImageSource.gallery);
                        CroppedFile? cropImageFile = await _cropImage(File(imageFile!.path));
                        if (cropImageFile != null) {
                          model.pickImage(ctx, File(cropImageFile.path));
                          Navigator.pop(context);
                        }
                      },
                      child: Container(
                        width: SysInfo.instance.deviceSize.width,
                        height: 60.0,
                        child: const Text('照片',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              height: 3.0,
                              fontSize: 16.0
                          ),
                        ),
                      ),
                    ),

                    Container(
                      height: 10.0,
                      color: UIData.windowBg,
                    ),

                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        Navigator.pop(context);
                      },
                      child: Container(
                        width: SysInfo.instance.deviceSize.width,
                        height: 60.0,
                        decoration: const BoxDecoration(
                            border: Border(
                                bottom: BorderSide(color: UIData.lineBg, width: UIData.lineH)
                            )
                        ),
                        child: const Text('取消',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              height: 3.0,
                              fontSize: 16.0
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              )
            ],
          );
        }
    );
  }

  Future<CroppedFile?> _cropImage(File imageFile) async {
    CroppedFile? croppedFile = await ImageCropper().cropImage(
      sourcePath: imageFile.path,
      aspectRatioPresets: [
        CropAspectRatioPreset.original,
        CropAspectRatioPreset.square,
        CropAspectRatioPreset.ratio3x2,
        CropAspectRatioPreset.ratio4x3,
        CropAspectRatioPreset.ratio16x9
      ],
      uiSettings: [
        AndroidUiSettings(
            toolbarTitle: '',
            toolbarColor: Colors.deepOrange,
            toolbarWidgetColor: Colors.white,
            initAspectRatio: CropAspectRatioPreset.original,
            lockAspectRatio: false),
        IOSUiSettings(
          title: '',
          cancelButtonTitle: '取消',
          doneButtonTitle: '确定',
        )
      ],
    );
    return croppedFile;
  }

}

@immutable
class Cell extends StatelessWidget {
  final String title;
  final String value;
  const Cell({Key? key, required this.title, required this.value}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 40.0,
      child: Row(
        children: [
          SizedBox(
            width: 80.0,
            child: Text(title),
          ),
          Text(value),
        ],
      ),
    );
  }
}